package com.mani.geotag;


import java.util.ArrayList;

import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ContactsDialog extends Dialog {

	public interface  ContactsItemCallBack{
		 void onContactsSelected(ArrayList<ContactsData> list);
	}
	ListView mListView;
	TextView mDone;
	Context mContext;
	ContactsItemCallBack mCB;
	ArrayList<ContactsData> mData;
	ArrayList<ContactsData> mSelectedData;
	EfficientAdapter mAdapter;
	private static int PORTRAIT_ORIENTATION = 1;
	private static int LANDSCAPE_ORIENTATION = 2;
	final String FONT_TTF = "bandless.ttf";
	static Typeface mFont;	
	Handler mHandler = new Handler();
	int mHeight;
	int mWidth;
	DisplayMetrics metrics = new DisplayMetrics();
	
	class ContactsData {
		String name;
		String phone;
		com.mani.geotag.CheckBoxView mCheckBox;
		ContactsData(String aname, String aphone) {
			name = aname;
			phone = aphone;
		}
		public void setCheckbox(com.mani.geotag.CheckBoxView CheckBox) {
			mCheckBox = CheckBox;
		}
	}
	DownloadWebPageTask mTask;
	public ContactsDialog(Context context,ContactsItemCallBack aCB) {
		super(context,R.style.contactsdialog);
		mContext = context;
		mCB = aCB;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.contactsdialog);
		mListView = (ListView) findViewById(R.id.contacts_list);
		mDone = (TextView) findViewById(R.id.done);
		mDone.setTypeface(getTypeface(context,FONT_TTF));
		mData = new ArrayList<ContactsData>();
		itemChecked = new ArrayList<Boolean>();
		mSelectedData = new ArrayList<ContactsData>();
		mAdapter = new EfficientAdapter(mContext);
		mListView.setAdapter(mAdapter);			
		mTask = new DownloadWebPageTask();
		mTask.execute("url");
		
		mDone.setOnClickListener( new View.OnClickListener() {
			@Override
			public void onClick(View v) {
					// Find the items selected.
					mCB.onContactsSelected(mData);
					ContactsDialog.this.dismiss();
			}
		});
		
	   WindowManager.LayoutParams params = getWindow().getAttributes();  

        if(getscreenOrientation() == PORTRAIT_ORIENTATION) {
	        params.height = (mHeight*75)/100;
	        params.width = (mWidth*90)/100;
        } else {
	        params.height = (mHeight*90)/100;
	        params.width = (mWidth*80)/100;
        }

        this.getWindow().setAttributes(params);	    

	}

	public void show() {
		super.show();
		// Reset the checkbox items
		for(int i=0;i<mData.size();i++) {
			if(mData.get(i).mCheckBox != null && mData.get(i).mCheckBox.isChecked() == true) {
				mData.get(i).mCheckBox.isCheckDrawn = false;
			}
		}	
	}

	public void stopThread() {
		mTask.cancel(true);
	}
	private class DownloadWebPageTask extends AsyncTask<String, Void, String> {

		protected String doInBackground(String... urls) {
			String url = null;
			LoadContacts();
			return url;
		}

		protected void onProgressUpdate(final Integer... values) {
			mAdapter.notifyDataSetChanged();	
	    }
		protected void onPostExecute(String url) {
			mAdapter.notifyDataSetChanged();	
		}
	}
    
	public static Typeface getTypeface(Context context, String typeface) {
	    if (mFont == null) {
	        mFont = Typeface.createFromAsset(context.getAssets(), typeface);
	    }
	    return mFont;
	}
	
	public int getscreenOrientation() {
		((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay().getMetrics(metrics);
		mWidth = metrics.widthPixels;
		mHeight = metrics.heightPixels;

		if (metrics.heightPixels > metrics.widthPixels)
			return PORTRAIT_ORIENTATION;
		else
			return LANDSCAPE_ORIENTATION;
	}

	private void LoadContacts() {
		ContentResolver cr = mContext.getContentResolver();
		Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
				null, null, null);
		int count = 0;
		if (cur.getCount() > 0) {

			while (cur.moveToNext() && mTask.isCancelled() == false) {
				
				String id = cur.getString(cur
						.getColumnIndex(ContactsContract.Contacts._ID));
				String name = cur
						.getString(cur
								.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				if (Integer
						.parseInt(cur.getString(cur
								.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
					System.out.println("name : " + name + ", ID : " + id);

					// get the phone number
					Cursor pCur = cr.query(
							ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
							null,
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID
									+ " = ?", new String[] { id }, null);

					while (pCur.moveToNext()) {
						count++;
						String phone = pCur
								.getString(pCur
										.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						mData.add(new ContactsData(name, phone));
						System.out.println("phone" + phone);
					}
					
					if(count%10 == 0) {
						mHandler.post( new Runnable() {
							public void run() {
								mAdapter.notifyDataSetChanged();
							}
						});
					}
					pCur.close();
				}
			} // End of while
		}
	}
	private ArrayList<Boolean> itemChecked;
	
	private class EfficientAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public EfficientAdapter(Context context) {
			// Cache the LayoutInflate to avoid asking for a new one each time.
			mInflater = LayoutInflater.from(context);
		}

		public int getCount() {
			itemChecked.clear();
			 for (int i = 0; i < mData.size(); i++) {
			        itemChecked.add(i, false); // initializes all items value with false
			  }
			return mData.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.contacts_listview,null);
				holder = new ViewHolder();
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.phone = (TextView) convertView.findViewById(R.id.phone);
				holder.name.setTypeface(getTypeface(mContext,FONT_TTF));
				holder.phone.setTypeface(getTypeface(mContext,FONT_TTF));
				holder.mCheckBox = (com.mani.geotag.CheckBoxView) convertView.findViewById(R.id.checkbox);
				mData.get(position).setCheckbox(holder.mCheckBox);				
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			} 
			holder.name.setText(mData.get(position).name);
			holder.phone.setText(mData.get(position).phone);
			com.mani.geotag.CheckBoxView cBox = holder.mCheckBox;
		    // CheckBox
		    cBox.setChecklistener(new com.mani.geotag.CheckBoxView.onCheckedChange() {

		        public void onCheckClick(View v) {
		        	com.mani.geotag.CheckBoxView cb = (com.mani.geotag.CheckBoxView) (v);
		            if (cb.isChecked()) {
		                itemChecked.set(position, true);
		            } else if (!cb.isChecked()) {
		                itemChecked.set(position, false);
		            }
		        }
		    }); 
		    
		    holder.mCheckBox.setCheckBox(itemChecked.get(position)); // this will Check or Uncheck

		    return convertView;
		}

		class ViewHolder {
			TextView name;
			TextView phone;
			com.mani.geotag.CheckBoxView mCheckBox;
		}
	}
}
